import tkFileDialog
from Tkinter import *
import tkMessageBox
import Image
import thread
from uploadImg import uploadImg
from uploadImg import uploadException

# ver.1 22/08/2013
# ver.2 22/08/2013 finish first exe version
# ver.3 22/08/2013  1 add mutithreading
#                   2 fix enableDoit bugs
#                   3 change text widget to message and hidden details
#                   Second exe version
#ver.4 02/09/2013 add upload
#ver.5 04/09/2013 release

# image process
class MyImage:
    quality = 100#quality of image
    size = -1 #resize image
    def __init__(self,quality,size = -1):
        self.quality = quality
        self.size = size
        
    def process(self,filename,savepath,savename):
        im = Image.open(filename)
        if self.size == -1 :
            print savepath+savename
            im.save(savepath+savename,quality = self.quality)
        else:
            radio = float(self.size)/im.size[0]
            height = int(im.size[1]* radio)
            min_im = im.resize((self.size, height), Image.BILINEAR)
            min_im.save(savepath+savename,quality = self.quality)

    
class mainBody:

    choosefile = False
    choosedir = False
    quality = 80
    size = -1
    # upload information
    loginurl = "http://www.lzq179.com/wp-login.php"
    uploadurl = "http://www.lzq179.com/wp-admin/media-new.php"
    loginpara = {
    'log':'lzq',
    'pwd':'lizequn',
    'wp-submit':'',
    'testcookie':1,
    'redirect_to':'http://www.lzq179.com/wp-admin/'
    }
    # upload control
    uploadjpgs = []
    isfinish = False
    def __init__(self,master):
        #frame init
        self.frame = Frame(master)
        self.frame.pack(side = TOP,fill = BOTH)
        
        #button open init
        self.but_open = Button(self.frame,text = "open",command = self.openFile)

        #button doit and upload init
        self.but_doit = Button(self.frame,text = "start",command = self.processing,state = DISABLED)
        self.but_upload = Button(self.frame,text="upload",command =self.doUpload ,state = DISABLED)

        #button choose dir
        self.but_choose = Button(self.frame,text="...",command = self.chooseDir)
              
        #lable_filename init
        self.filename = StringVar()
        self.filename.set("empty")
        self.lab_file = Label(self.frame,textvariable = self.filename)

        #label_gui init
        self.lab_in = Label(self.frame,text="input:")
        self.lab_out = Label(self.frame,text="output:")

        #entry_file output
        self.save_file = StringVar()
        self.save_file.set("")
        self.ent_file = Entry(self.frame,textvariable = self.save_file)

        #label_quality and size
        self.lab_qua = Label(self.frame,text = "quality(%):")
        self.lab_size = Label(self.frame,text = "size(px):")

        #label_entry quality and size
        self.ent_qua = Entry(self.frame)
        self.ent_size = Entry(self.frame)
 
        #grid
        self.lab_in.grid(row = 0,sticky = W)
        self.lab_file.grid(row = 0,column = 1,sticky = N)
        self.but_open.grid(row = 0,column = 2,sticky = E)
        self.lab_qua.grid(row = 0,column = 3,sticky = W)
        self.ent_qua.grid(row = 0,column = 4,sticky = W)
        self.lab_out.grid(row = 1,sticky = W)
        self.ent_file.grid(row = 1,column = 1,sticky = W+E)
        self.but_choose.grid(row =1,column = 2,sticky = W)
        self.lab_size.grid(row = 1,column = 3,sticky = E)
        self.ent_size.grid(row = 1,column = 4,sticky = W)
        self.but_doit.grid(row = 2, column = 1,padx = 1,pady = 1)
        self.but_upload.grid(row = 2, column = 2)

        #text
        #self.text = Text(master,bg="black",fg = "white",state=DISABLED,yscrollcommand = True,width = 50)
        #self.text.pack()
        #message 1
        self.text = StringVar()
        self.text.set("welcome...")
        self.mess = Message(master,textvariable =self.text,anchor = NW,width = 100)
        self.mess.pack(fill = BOTH)
        #message 2 for upload
        self.text2 = StringVar()
        self.text2.set("wait for upload")
        self.mess2 = Message(master,textvariable =self.text2,anchor = NW,width = 100)
        self.mess2.pack(fill = BOTH)

        
        
    #open photos
    def openFile(self):
        self.jpgname = tkFileDialog.askopenfilenames(filetypes=[("jpg file", "*.jpg"),("all","*.*")]) #get files path
        self.jpgnames = self.jpgname.split() #split and put into []
        self.filename.set("num: " +str(len(self.jpgnames)))
        if len(self.jpgnames)>0 :
            self.choosefile = True
            self.enableDoit()
        
    
    #choose a dir to save photos
    def chooseDir(self):
        self.directory = tkFileDialog.askdirectory()
        
        if len(self.directory) >0 :
            if self.directory[-1] != "/":
                self.directory += "/"
            self.save_file.set(self.directory)
            self.choosedir = True
            self.enableDoit()

    #do condense and get original name and save name
    def processing(self):
        if len(self.jpgnames) > 0 :
            
            if not self.checkNum(self.ent_qua): # check if all is number
                return 
            if not self.checkNum(self.ent_size):
                return
            if len(self.ent_qua.get()) >0:  #get quality
                self.quality = int(self.ent_qua.get())
                if self.quality>100 or self.quality <1:
                    self.quality = 100
            if len(self.ent_size.get()) >0: #get size
                self.size = int(self.ent_size.get())
                if self.size <1:
                    self.size = -1
            #lock input
            #self.text.config(state=NORMAL) 
            self.ent_qua.config(state = DISABLED)
            self.ent_size.config(state = DISABLED)
            thread.start_new_thread(self.doCompress,())


    #for mutithreading
    def doCompress(self):
        self.count = 0 #count for images
        im = MyImage(self.quality,self.size)#create Image process object
        
        for jpgfile in self.jpgnames :
            self.count+=1
            #self.text.insert(INSERT,"no"+str(self.count)+": "+self.getOldName(jpgfile)+" ---")
            #self.text.insert(INSERT,str(self.count)+"/" + str(len(self.jpgnames))+"\n")
            #self.text.set( self.text.get() + "no"+str(self.count)+": "+self.getOldName(jpgfile)+" ---"+str(self.count)+"/" + str(len(self.jpgnames))+"\n")
            self.text.set(str(self.count)+"/" + str(len(self.jpgnames))+"\n")
            im.process(jpgfile,self.directory,self.getNewName(jpgfile))
            self.uploadjpgs.append(self.directory+self.getNewName(jpgfile))
        self.clean()
   

    # for upload
    def doUpload(self):
        if self.isfinish :
            self.isfinish = False
            try:
                self.text2.set("create")
                self.upimg = uploadImg(self.loginurl,self.uploadurl,**self.loginpara)   
            except uploadException, e:
                 tkMessageBox.showerror("Only Nums",e.error)
            self.text2.set("upload begin")
            thread.start_new_thread(self.uploading,())
        else:
            self.isfinish = False
            return False


    #for multiprocess
    def uploading(self):
        if not self.upimg.isinit:
            self.text2.set("init begin")
            self.upimg.init()
            self.text2.set("init finish")
        count = 0
        for jpg in self.uploadjpgs:
            count+=1
            code = self.upimg.do_upload(jpg)
            if code == 200:
                self.text2.set(str(count) + "/"+str(len(self.uploadjpgs)))
            else:
                self.text2.set(str(count) + "/"+str(len(self.uploadjpgs))+"error:"+code)
                break
        self.uploadclean()


    #get old name
    def getOldName(self,name):
        return name.split("/")[-1]
    #get new name
    def getNewName(self,name):
        newname = name.split("/")[-1].split(".")[0]
        newname = newname + "_small"+".jpg"
        return newname

    #enable doit button
    def enableDoit(self):
        if self.choosedir and self.choosefile :
            self.but_doit.config(state = NORMAL)
        else:
            self.but_doit.config(state = DISABLED)

    #check nums
    def checkNum(self,ent):
        print "do"
        l = list(ent.get())
        for i in range(len(l)-1,-1,-1):
            if not (48<= ord(l[i])<=57):
                ent.delete(0,END)
                tkMessageBox.showerror("Only Nums","Please input numbers!")
                return False
        return True
    def clean(self):
        #self.text.config(state=DISABLED)
        self.ent_qua.config(state = NORMAL)
        self.ent_size.config(state = NORMAL)
        #self.choosedir = False
        self.choosefile = False
        self.enableDoit()
        self.filename.set("empty")
        self.isfinish=True
        self.but_upload.config(state = NORMAL)
        #self.ent_file.delete(0,END)
    def uploadclean(self):
        self.but_upload.config(state = DISABLED)
        self.uploadjpgs = []

   
root = Tk()
root.title("JPG Compression by Zzz")
root.resizable(False,False)
body = mainBody(root)

root.mainloop()
